package cn.zsxmlv.modules.sys.ctrl;

import cn.zsxmlv.common.utils.Constant;
import cn.zsxmlv.common.utils.PageUtils;
import cn.zsxmlv.common.utils.R;
import cn.zsxmlv.common.validator.ValidatorUtils;
import cn.zsxmlv.modules.sys.entity.SysRoleEntity;
import cn.zsxmlv.modules.sys.service.SysRoleMenuService;
import cn.zsxmlv.modules.sys.service.SysRoleService;
import cn.zsxmlv.modules.sys.service.SysUserRoleService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zs
 * @description: 角色管理
 * @date: 2019/2/27 9:27
 */
@RestController
@RequestMapping("/sys/role")
@Api(tags = "角色管理")
public class SysRoleCtrl extends BaseCtrl {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 获取所有的角色数据
     * @return
     */
    @RequestMapping("/selectAllRole")
    public R selectAllRole() {
        List<SysRoleEntity> list = sysRoleService.selectList(null);
        return R.ok().put("list", list);
    }

    /**
     * 根据用户ID获取用户的角色列表
     * @return
     */
    @RequestMapping("/selectByUserId")
    public R selectByUserId(Integer userId) {
        List<SysRoleEntity> list = sysRoleService.selectByUserId(userId);
        return R.ok().put("list", list);
    }

    @RequestMapping("/selectByRoleName")
    public R selectByRoleName(String roleName) {
        sysRoleService.selectByRoleName(roleName);
        return R.ok();
    }

    @RequestMapping("/list")
    public R list(@RequestParam Map<String,Object> params) {
        // 创建人ID为0表示超级管理员 如果不是超管则只能查询自己创建的角色
        params.put("createUserId", 0);
        if (getUser().getCreateUserId() != Constant.SUPER_ADMIN){
            params.put("createUserId", getUserId());
        }

        PageUtils page = sysRoleService.queryPage(params);

        return R.ok().put("page", page);
    }

    @PostMapping("/save")
    public R save(@RequestBody SysRoleEntity role) {
        ValidatorUtils.validateEntity(role);

        int cid = getUser().getCreateUserId() == 0 ? 0 : getUserId();

        role.setCreateUserId(cid);
        sysRoleService.save(role);

        return R.ok();
    }

    @RequestMapping("/info/{roleId}")
    public R info(@PathVariable Integer roleId) {
        SysRoleEntity entity = sysRoleService.selectById(roleId);

        List<Integer> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
        entity.setMenuIdList(menuIdList);

        return R.ok().put("role", entity);
    }

    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] roleIds) {

        sysRoleService.deleteBatch(roleIds);

        return R.ok();
    }
}
